package com.redare.dev.smart.generator.workbench.controller;

import com.redare.dev.smart.generator.sdk.pojo.form.GeneratorSysForm;
import com.redare.dev.smart.generator.sdk.utils.StringUtils;
import com.redare.devframework.common.pojo.CommonResult;
import com.redare.devframework.webplatform.workbench.controller.component.BaseWebController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @date 2021-08-28 23:03:12
 * Created by yangqiangyu
 */

@RequestMapping(value = "/api/_generator_api/dir")
@Controller
public class DirController extends BaseWebController {

    @ResponseBody
    @RequestMapping(value = "/findDirectory", method = RequestMethod.POST)
    public CommonResult<List<Map<String,Object>>> findDirectory(
            @RequestBody GeneratorSysForm.Add form,
            @RequestParam(required = false) String path
    ) {
        List<Map<String,Object>> resultList = new ArrayList<>();
        if (StringUtils.isBlank(path)){
            File[] files = File.listRoots();
            getResultList(resultList, files);
            return CommonResult.returnDataWrapper(resultList);
        }else{
            File dir = new File(path);
            if (!dir.exists()&&dir.isDirectory()){
                return CommonResult.returnDataWrapper(null);
            }
            File[] files = dir.listFiles();
            getResultList(resultList, files);
        }
        return CommonResult.returnDataWrapper(resultList);

    }

    private void getResultList(List<Map<String, Object>> resultList, File[] files) {
        if (files==null){
            return;
        }
        for (File file : files) {
            Map<String,Object> map = new HashMap(3);
            map.put("title",file.getName());
            map.put("key",file.getAbsolutePath());
            map.put("path",file.getAbsolutePath());
            resultList.add(map);
        }
    }

}